import os
import shutil
import stat
import zipfile
'''
    读取文件下的所有文件
    @author xuyan
'''
def readDir(dir):
    return os.listdir(dir)

def url2FileName(fileUrl):
    filename = os.path.basename(fileUrl)
    return filename

def dirIsExists(dir):
    return os.path.exists(dir)

def mkDir(path):
    return os.makedirs(path)

def delFile(file):
    try:
        os.chmod(file, stat.S_IRWXO + stat.S_IRWXG | stat.S_IRWXU)
        if os.path.isdir(file):
            del_list = os.listdir(file)
            for f in del_list:
                file_path = os.path.join(file, f)
                if os.path.isfile(file_path):
                    os.remove(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            shutil.rmtree(file)
        elif os.path.isfile(file):
            os.remove(file)
        return True
    except :
        return False

def readFile(path):
    apkList = []
    if os.path.isfile(path) and path.endswith(".apk"):
        apkList.append(path)
    elif os.path.isdir(path):
        dirs = readDir(path)
        for d in dirs:
            apkList.extend(readFile((path+"/"+d).replace("//","/")))
    return apkList

def canculateCRC(file,key):
    allCRC = 0
    if dirIsExists(file):
        zipFile = zipfile.ZipFile(file)
        for info in zipFile.infolist():
            if key in info.filename:
                allCRC = allCRC + int(info.CRC)
        print(key+":"+str(allCRC))
    return str(allCRC)

#移除文件夹下所有文件
def del_dir_in_files(path):
    if os.path.exists(path):
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                del_dir_in_files(c_path)
                os.rmdir(c_path)
            else:
                os.remove(c_path)

#拷贝文件夹
def copy_file(sourceDir, targetDir):
    for f in os.listdir(sourceDir):
        sourceF = os.path.join(sourceDir,f)
        targetF = os.path.join(targetDir,f)
        if os.path.isfile(sourceF):
            do_copy_file(sourceF,targetF)
        if os.path.isdir(sourceF):
            copy_file(sourceF,targetDir)

def do_copy_file(src_file, dst):
    shutil.copy(src_file, dst)

# if __name__ == '__main__':
#     dexCrc = canculateCRC("/Users/xuyan/Desktop/eng100-student-apk/Baidu/release/eng100-student-1.2.16-Baidu-release.apk",".dex")
#     print(dexCrc)